package datastructures;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/19 11:22
 * 稀疏数组
 */
public class SpareArray {
    public static void main(String[] args) {
        //创建一个二维数组 11*11
        //0 没有其志， 1 表示黑子，2表示其他
        int chessArr1[][] = new int[11][11];

        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[3][3] = 1;
        System.out.println("原始二维数组");
        for (int[] ints : chessArr1) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }
        //二维数组转成稀疏数组
        //    1 遍历二维数组，得到非0 数据个数
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    sum++;
                }
            }
        }

        //    2 创建对应的稀疏数组
        int spareArr[][] = new int[sum + 1][3];
        spareArr[0][0] = 11;
        spareArr[0][1] = 11;
        spareArr[0][2] = sum;

        //记录是第几个非0数据
        int col = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr1[i][j] != 0) {
                    col++;
                    spareArr[col][0] = i;
                    spareArr[col][1] = j;
                    spareArr[col][2] = chessArr1[i][j];
                }
            }
        }

        System.out.println("输出稀疏数组");
        print(spareArr);
        System.out.println("稀疏数组恢复成原始数组");
        int[][] newChess = new int[spareArr[0][0]][spareArr[0][1]];

        for (int i = 1; i < spareArr.length; i++) {
            newChess[spareArr[i][0]][spareArr[i][1]] = spareArr[i][2];
        }
        print(newChess);
    }

    private static void print(int[][] arr) {
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }
    }
}
